package com.chat.provider.core;

import com.chat.server.base.MetadataUnit;
import com.chat.server.base.PackageMeta;
import com.chat.server.base.ServiceRegister;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @Auther created by haoteng on 2019/08/20
 */
public class RegisterContext {

    static Logger logger = LoggerFactory.getLogger(RegisterContext.class);

    public static final Multimap<String, MetadataUnit> registerMetadataMap = ArrayListMultimap.create();

    public static ServiceRegister serviceRegister = new ServiceRegister();

    /**
     * 注册管理
     *
     * @param packageMeta
     * @param data
     */
    private void doRegister(PackageMeta packageMeta, Object data) {
        String packageName = packageMeta.getPackagePath();
        Boolean result = serviceRegister.register(packageName, data);
        if (result) {
            logger.info(packageName + " register success!");
        } else {
            logger.info(packageName + " register is failed!");
        }
    }

    public Boolean registerServers(Class clazz) {
        // 获取本地ip
        try {
            InetAddress inetAddress = InetAddress.getLocalHost();
            String ip = inetAddress.getHostAddress();
            ip = "localhost";
            PackageMeta packageMeta = new PackageMeta();
            packageMeta.setIp(ip);
            Class[] classes = clazz.getInterfaces();
            packageMeta.setInterfacePath(classes[0].getName());
            packageMeta.setPort(8888);
            // 节点保存数据
            MetadataUnit metadataUnit = new MetadataUnit();
            metadataUnit.setIp(ip);
            metadataUnit.setPort(8888);
            metadataUnit.setServicePath(clazz.getName());
            String interfaceName = classes[0].getName();
            metadataUnit.setInterfaceName(interfaceName);
            doRegister(packageMeta, metadataUnit);
            return true;
        } catch (Exception e) {
            logger.error("获取本地ip失败");
            return false;
        }
    }

    public static void main(String[] args) throws UnknownHostException {
        InetAddress inetAddress = InetAddress.getLocalHost();
        String ip = inetAddress.getHostAddress();
        System.out.println(ip);
    }
}

